package com.hyl.controller;

import com.hyl.entity.SysUser;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Description TODO
 * @Author hyl
 * @Date 2023/5/12 9:47
 **/
@Controller
public class LoginController {

	/*
	*
	* ModelAndView
	*   model:模型==》数据封装==》request
	*   view:视图 ==》视图名==》视图解析器[前缀、后缀]==》生成最终的页面跳转地址==》转发
	*        去到另一个请求==》重定向 =》redirect:请求的路径
	* */

	//提交方式：get
	@GetMapping("/login1")
	protected ModelAndView login1(HttpServletRequest request) throws Exception {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("loginName","hyl"); //requset.setAttribute();
		modelAndView.setViewName("frame"); //\WEB-INF\jsp\frame.jsp
		return modelAndView;
	}


	//提交方式：get
	@GetMapping("/login")
	protected String login(@RequestParam(required = false,defaultValue = "admin") String account,
	                       @RequestParam(required = false,defaultValue = "123456") String password,
	                       HttpSession session){
		System.out.println("登入："+account);
		//逻辑
		if(!account.equals("hyl")){
			//异常
			throw  new RuntimeException("登录异常");
		}

		//保存登入用户信息
		session.setAttribute("userSession", account);
		return "frame"; //视图名称
	}
	//提交方式：post
	@PostMapping("/regist")
	protected String reg(SysUser user) throws Exception {

		return "frame";//视图名称
	}

	//提交方式：任意
	@RequestMapping("/logout")
	protected String logout() throws Exception {
		return "login";//视图名称
	}

	//局部异常处理==》作用于当前Contoller
	@ExceptionHandler(value = {RuntimeException.class})
	public String exp(HttpServletRequest request,RuntimeException e){
		request.setAttribute("exception", e); //消息需要程序员，自己进行定义
		return "sysError";//视图名称
	}
}
